﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SIMS.Shared.DTO;
using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;

namespace SIMS.SqlSugarWebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _service;
        private readonly IMapper _mapper;

        public UserController(IUserService service, IMapper mapper)
        {
            _service = service;
            _mapper = mapper;
        }

        [HttpPost]
        public async Task<IActionResult> AddUser(UserDTO u)
        {
            var user = _mapper.Map<User>(u);
            var data = await _service.AddEntity(user);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteUser(int id)
        {
            var data = await _service.DeleteEntity(id);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> GetUser(int id)
        {
            var data = await _service.GetEntity(id);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpPut]
        public async Task<IActionResult> UpdateUser(UserDTO u)
        {
            var user = _mapper.Map<User>(u);
            var data = await _service.UpdateEntity(user);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> GetUsers(int pageNum, int pageSize, string? userName)
        {
            var data = await _service.GetUsers(userName, pageNum, pageSize);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public IActionResult GetUserRoles(int? userId)
        {
            var data = _service.GetUserRoles(userId);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> SetUserRoles(int userId, string roleIds)
        {
            var data = await _service.SetUserRoles(userId, roleIds);
            var res = new ResponseResultModel() { data = data };
            return Ok(res);
        } 
    }
}
